<?php

namespace App\Http\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class RedPacket extends Model
{
    /**
     * 获取红包信息
     *
     * @param $user_id
     * @return array [轮数, 喂食次数]
     */
    public static function get($uid) {
        $user_info = DB::table('users')->where('id', $uid)->first();
        return [
            'cycle' => $user_info['rp_cycle'] ?? 1,
            'feed_times' => $user_info['rp_feed_times'] ?? 0,
            'receive_times' => $user_info['rp_receive'] ?? 0,
        ];
    }

    public static function set($uid, $nums = 1) {
        $info = self::get($uid);
        // 判断是否满足增加条件
        $reward_info = self::nextReward($uid);
        if(!empty($reward_info) && $reward_info['times'] != $info['feed_times']) {
            DB::table('users')->where(['id'=>$uid])->increment('rp_feed_times', $nums);
        }
    }

    /**
     * 获取下一个可领取的奖励
     */
    public static function nextReward($uid, $info = null) {
        if($info === null) $info = self::get($uid);
        if($info['feed_times'] == $info['receive_times']) $info['feed_times']++;
        // 根据用户当前轮数读取
        $config = DB::table('red_packet')->where('cycle', $info['cycle'])->orderBy('times', 'asc')->get();
        if(!count($config)) {
            // 未读取到, 读取设置为0
            $config = DB::table('red_packet')->where('cycle', 0)->orderBy('times', 'asc')->get();
        }
        if(empty($config)) return [];
        foreach($config as $arr) {
            if($arr['times'] >= $info['feed_times']) {
                $arr['rewards'] = json_decode($arr['rewards'], true);
                // 处理优惠券库存
                foreach($arr['rewards'] as $key=>$re) {
                    if($re['type'] == 3) {
                        $coupon_info = DB::table('red_packet_coupon')->where(['id'=>$re['id']])->where('inventory','>',0)->first();
                        if(empty($coupon_info)) {
                            unset($arr['rewards'][$key]);
                        }
                    }
                }
                return $arr;
            }
        }
        return false;
    }
}
